package com.xbongbong.coolapp;

import com.alibaba.dingtalk.openapi.helper.DingCoolAppHelper;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkim_1_0.models.InteractiveCardCreateInstanceRequest;
import com.aliyun.dingtalkim_1_0.models.PrivateDataValue;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest;
import com.aliyun.dingtalkim_1_0.models.SendRobotInteractiveCardRequest;
import com.aliyun.dingtalkim_1_0.models.UpdateInteractiveCardRequest;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.util.URLEncodeUtils;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.coolapp.pojo.CardDataPojo;
import com.xbongbong.pro.enums.coolapp.enums.CardTypeEnum;
import com.xbongbong.pro.enums.coolapp.enums.CardUseSceneEnum;
import com.xbongbong.pro.service.cool.app.BizManagerHelp;
import com.xbongbong.saas.domain.entity.CoolAppCardDataEntity;
import com.xbongbong.saas.domain.entity.CoolAppCardTemplateEntity;
import com.xbongbong.saas.model.CoolAppCardTemplateModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: hongxiao
 * @date: 2022-05-26 20:27
 */
@Service("bizManager")
public class BizManager {

    private static  final Logger LOG = LoggerFactory.getLogger(BizManager.class);

    @Resource
    private CoolAppCardTemplateModel coolAppCardTemplateModel;
    @Resource
    private DingCoolAppHelper dingCoolAppHelper;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private BizManagerHelp bizManagerHelp;


    /**
     * 安装酷应用后卡片
     * 卡片
     *      内容：宣传图；宣传内容
     *      按钮：快速体验(新建客户表单)；使用指南(帮助中心)
     */

    public void sendWelcomeCard(String accessToken, String corpid, String openConversationId, String robotCode, Boolean isAddCustomer, Long appId, Long menuId, Long formId) {
        // 欢迎语卡片模板
        CoolAppCardTemplateEntity coolAppCardTemplateEntity = coolAppCardTemplateModel.getByUseScene(CardTypeEnum.IM_CARD.getType(), CardUseSceneEnum.WELCOME.getType());
        if (Objects.isNull(coolAppCardTemplateEntity)) {
            return;
        }

        // 发送选项
        SendRobotInteractiveCardRequest.SendRobotInteractiveCardRequestSendOptions sendOptions = new SendRobotInteractiveCardRequest.SendRobotInteractiveCardRequestSendOptions();
        sendOptions.setAtAll(true);
        // 生成cardBizId
        String cardBizId = UUID.randomUUID().toString();
        // 互动卡片高级版
        SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = getWelcomeCardData(corpid, openConversationId, isAddCustomer, appId, menuId, formId);
        // 客户表单

        dingCoolAppHelper.sendInteractiveCard(accessToken, openConversationId, robotCode, coolAppCardTemplateEntity.getCardId(), null, cardBizId, cardData, null, null, null, null);
    }

    /***
     * 欢迎语卡片内容
     *
     * @param
     * @throws
     * @return SendInteractiveCardRequestCardData
     * @author hongxiao
     * @date 2022-06-20 19:23
     * @since
     * @version
     */
    private SendInteractiveCardRequest.SendInteractiveCardRequestCardData getWelcomeCardData(String corpid, String openConversationId, Boolean isAddCustomer, Long appId, Long menuId, Long formId) {
        SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = new SendInteractiveCardRequest.SendInteractiveCardRequestCardData();
        Map<String, String> cardParamMap = new HashMap<>();

        // 体验按钮
        if (isAddCustomer) {
            String baseUrl = proBaseConfig.getPushFrontUrl() + "index.html?corpid=" + corpid + "&appid=" + Env.DING_XBB_APP_ID + "&openConversationId=" + openConversationId + "#";
            String addDataUrl = "/application/newForm?appId=" + appId + "&menuId=" + menuId + "&formId=" + formId + "&saasMark=1&distributorMark=0&businessType=100&subBusinessType=101";
            String pcUrl = "dingtalk://dingtalkclient/page/link?pc_slide=true&url=" + URLEncodeUtils.encodeURL(baseUrl + addDataUrl);
            String mobileUrl = "dingtalk://dingtalkclient/action/im_open_hybrid_panel?panelHeight=percent70&hybridType=online&pageUrl=" + URLEncodeUtils.encodeURL(baseUrl + addDataUrl);
            JSONObject addCustomer = new JSONObject();
            addCustomer.put("pcUrl", pcUrl);
            addCustomer.put("mobileUrl", mobileUrl);
            addCustomer.put("name", "快速检验");
            Map<String, Object> cardMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            cardMap.put("addCustomer", addCustomer);
            cardMap.put("MV", "https://xbbpro.oss-cn-zhangjiakou.aliyuncs.com/helpcenter/2022/kuapp.mp4");
            cardParamMap.put("sys_full_json_obj", JSON.toJSONString(cardMap));
        }

        cardData.setCardParamMap(cardParamMap);
        return cardData;
    }

    /**
     * 发送机器人卡片
     *
     * @param accessToken
     * @param openConversationId
     * @param robotCode
     * @param cardTemplateId
     * @param callbackUrl
     * @param cardBizId
     * @param cardData
     * @param cardPrivateData
     * @return
     */
    public String sendRobotCard(String accessToken, String openConversationId, String robotCode, String cardTemplateId, String callbackUrl, String cardBizId,
                                JSONObject cardData, JSONObject cardPrivateData) {
        // 机器人卡片的sendOptions外层拼好传进来
        SendRobotInteractiveCardRequest.SendRobotInteractiveCardRequestSendOptions sendOptions = new SendRobotInteractiveCardRequest.SendRobotInteractiveCardRequestSendOptions();
        return dingCoolAppHelper.sendRobotInteractiveCard(accessToken, openConversationId, robotCode, cardTemplateId, callbackUrl, cardBizId, cardData, cardPrivateData, sendOptions);
    }

    /**
     * 更新机器人卡片
     *
     * @param accessToken
     * @param cardBizId
     * @param cardData
     * @param cardPrivateData
     * @return
     */
    public String updateRobotCard(String accessToken, String cardBizId, JSONObject cardData, JSONObject cardPrivateData) {
        return dingCoolAppHelper.updateRobotInteractiveCard(accessToken, cardBizId, cardData, cardPrivateData);
    }


    /**
     * 发送互动卡片
     *
     * @param accessToken
     * @param cardDataEntity
     * @param cardData
     * @return
     */
    public String sendCard(String accessToken, CoolAppCardDataEntity cardDataEntity, CardDataPojo cardData) {
        return bizManagerHelp.sendCard(accessToken, cardDataEntity, cardData);
    }

    /**
     * 更新互动卡片
     *
     * @param accessToken
     * @param cardBizId
     * @param cardData
     * @return
     */
    public Boolean updateCard(String accessToken, String cardBizId, CardDataPojo cardData){

        // 共公数据
        UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData updateCardData = new UpdateInteractiveCardRequest.UpdateInteractiveCardRequestCardData();
        updateCardData.setCardParamMap(cardData.getCardParamMap());
        // 私有数据
        Map<String, PrivateDataValue > updateCardPrivateData = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(cardData.getCardPrivateData())) {
            for (Map.Entry<String, Map<String, String>> entry : cardData.getCardPrivateData().entrySet()) {
                String key = entry.getKey();
                Map<String, String> value = entry.getValue();
                PrivateDataValue privateDataValue = new PrivateDataValue();
                privateDataValue.setCardParamMap(value);
                updateCardPrivateData.put(key, privateDataValue);
            }
        }

        return dingCoolAppHelper.updateInteractiveCard(accessToken,cardBizId,updateCardData,updateCardPrivateData);
    }

    /***
     * 发送吊顶卡片
     *
     * @param: accessToken
     * @param: cardDataEntity
     * @param: cardData
     * @param: cardPrivateData
     * @throws
     * @return java.lang.String
     * @author hongxiao
     * @date 2022-06-13 10:27
     * @since
     * @version
     */
    public String sendTopCard(String accessToken, CoolAppCardDataEntity cardDataEntity, CardDataPojo cardData) {
        return bizManagerHelp.sendTopCard(accessToken, cardDataEntity, cardData);
    }


    /**
     * 关闭吊顶卡片
     *
     * @param accessToken
     * @param cardDataEntity
     * @return
     */
    public Boolean closeTopCard(String accessToken, CoolAppCardDataEntity cardDataEntity, List<String> userIds) {
        return dingCoolAppHelper.interactiveCardTopBoxesClose(accessToken, cardDataEntity.getOpenConversationId(), proBaseConfig.getCoolAppCode(), cardDataEntity.getCardBizId(), userIds);
    }

}
